package com.example.mallsystem1104.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mallsystem1104.constants.Constants;
import com.example.mallsystem1104.entity.MyFile;
import com.example.mallsystem1104.exception.ServiceException;
import com.example.mallsystem1104.mapper.FileMapper;
import com.sun.xml.fastinfoset.stax.events.Util;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Locale;

/**
 * @Author zy
 * @Date 2024/12/10 17:20
 * @packageName:com.example.mallsystem1104.service
 * @ClassName:FileService
 */
@Service
public class FileService extends ServiceImpl<FileMapper, MyFile> {
    @Resource
    private FileMapper fileMapper;

    public void download(String fileName, HttpServletResponse response) {
        File file=new File(Constants.fileFolderPath+fileName);
        if(!file.exists()){
            throw new ServiceException(Constants.CODE_500,"文件不存在");
        }
        try {
            ServletOutputStream os=response.getOutputStream();
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            response.setContentType("application/octet-stream");
            os.write(FileUtil.readBytes(file));
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String type = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        long size=file.getSize()/1024;//单位kb
        String url;
        //用于保存于数据库的实体类files
        MyFile myFile=new MyFile();
        myFile.setName(originalFilename);
        myFile.setType(type);
        myFile.setSize(size);

        // 通过md5加密方式判断文件是否已存在
        InputStream inputStream=null;
        try {
            inputStream=file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String md5= SecureUtil.md5(inputStream);
        QueryWrapper<MyFile> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("md5",md5);
        List<MyFile> dbMyFileList = fileMapper.selectList(queryWrapper);
        if(dbMyFileList.size()!=0){
            //数据库里已经有该文件的md5格式，拷贝他的URL
            url=dbMyFileList.get(0).getUrl();
            myFile.setUrl(url);
        }else {
            //文件不存在则保存文件
            File folder=new File(Constants.fileFolderPath);
            if(!folder.exists()){
                folder.mkdirs();
            }
            //文件存储文件夹的位置
            String folderPath=folder.getAbsolutePath()+"/";
            System.out.println("文件存储地址"+folderPath);
            //将文件保存为uuid的名字，通过uuid生成url
            String uuid= UUID.randomUUID().toString().replace("-","").toLowerCase();
            String finalFileName=uuid+"."+type;
            File targetFile=new File(folder+finalFileName);
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            url="/file/"+finalFileName;
            myFile.setUrl(url);
        }
        myFile.setMd5(md5);

        fileMapper.insert(myFile);
        return url;
    }

    public int deleteById(int id) {
        UpdateWrapper<MyFile> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",id).set("is_delete",true);
        return fileMapper.update(null,updateWrapper);
    }

    public IPage<MyFile> selectPage(int pageNum, int pageSize, String fileName) {
        IPage<MyFile> myFileIPage=new Page<>(pageNum,pageSize);
        QueryWrapper<MyFile> queryWrapper=new QueryWrapper<>();
        if(!Util.isEmptyString(fileName)){
            queryWrapper.like("name",fileName);
        }
        queryWrapper.eq("is_delete",fileName);
        queryWrapper.orderByDesc("id");
        return page(myFileIPage,queryWrapper);
    }
}
